package com.bookstore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bookstore.entity.Category;
import com.bookstore.mapper.CategoryMapper;
import com.bookstore.service.CategoryService;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Override
    public boolean addCategory(Category category) {
        return save(category);
    }

    @Override
    public boolean updateCategory(Category category) {
        return updateById(category);
    }

    @Override
    public boolean deleteCategory(Integer categoryId) {
        // 检查是否有子分类
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getParentId, categoryId);
        if (count(queryWrapper) > 0) {
            throw new IllegalArgumentException("该分类下有子分类，无法删除");
        }
        return removeById(categoryId);
    }

    @Override
    public List<Category> getCategoryList() {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Category::getSort);
        return list(queryWrapper);
    }

    @Override
    public List<Category> getSubCategoryList(Integer parentId) {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getParentId, parentId)
                .orderByAsc(Category::getSort);
        return list(queryWrapper);
    }

    @Override
    public List<Category> getCategoryTree() {
        List<Category> allCategories = getCategoryList();
        Map<Integer, List<Category>> parentMap = allCategories.stream()
                .collect(Collectors.groupingBy(Category::getParentId));

        // 获取根分类（parentId为0或null的分类）
        List<Category> rootCategories = parentMap.getOrDefault(0, new ArrayList<>());
        if (rootCategories.isEmpty()) {
            rootCategories = parentMap.getOrDefault(null, new ArrayList<>());
        }

        // 递归构建树形结构
        rootCategories.forEach(root -> buildCategoryTree(root, parentMap));

        return rootCategories;
    }

    private void buildCategoryTree(Category category, Map<Integer, List<Category>> parentMap) {
        List<Category> children = parentMap.getOrDefault(category.getCategoryId(), new ArrayList<>());
        category.setChildren(children);
        children.forEach(child -> buildCategoryTree(child, parentMap));
    }
} 